import { RedisClientOptions } from '@liaoliaots/nestjs-redis'
import { HttpModule } from '@nestjs/axios'
import { Module } from '@nestjs/common'
import { ConfigModule, ConfigService } from '@nestjs/config'
import { APP_GUARD } from '@nestjs/core'
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm'
import { JwtAuthGuard } from './common/guards/auth.guard'
import { RolesGuard } from './common/guards/roles.guard'
import configuration from './config/index'
import { MainModule } from './modules/main/main.module'
import { RedisModule } from './modules/redis/redis.module'
import { AuthModule } from './modules/system/auth/auth.module'
import { DeptModule } from './modules/system/dept/dept.module'
import { DictModule } from './modules/system/dict/dict.module'
import { MenuModule } from './modules/system/menu/menu.module'
import { UserModule } from './modules/system/user/user.module'

@Module({
  imports: [
    // 配置模块
    ConfigModule.forRoot({
      cache: true,
      load: [configuration],
      isGlobal: true
    }),
    // 数据库链接
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => {
        return {
          type: 'mysql',
          entities: [`${__dirname}/**/*.entity{.ts,.js}`],
          autoLoadEntities: true,
          keepConnectionAlive: true,
          timezone: '+08:00',
          ...config.get('db.mysql')
        } as TypeOrmModuleOptions
      }
    }),
    // redis
    RedisModule.forRootAsync(
      {
        imports: [ConfigModule],
        inject: [ConfigService],
        useFactory: (config: ConfigService) => {
          return {
            closeClient: true,
            readyLog: true,
            errorLog: true,
            config: config.get<RedisClientOptions>('redis')
          }
        }
      },
      true
    ),
    HttpModule,
    AuthModule,
    MainModule,
    UserModule,
    MenuModule,
    DictModule,
    DeptModule
  ],
  providers: [
    {
      provide: APP_GUARD,
      useClass: JwtAuthGuard
    },
    {
      provide: APP_GUARD,
      useClass: RolesGuard
    }
  ]
})
export class AppModule {}
